﻿using System;
using System.Collections.Generic;

using System.Text;

namespace DotNETX.Authentication
{
    public class Authenticater : IAuthenticater
    {
        public Authenticater()
        {
            TokenManager = new BasicTokenManager();
        }

        public Authenticater(IUserManager userManager, ITokenManager tokenManager)
        {
            UserManager = userManager;
            TokenManager = tokenManager;
        }

        #region IAuthenticater

        public virtual string Login(string lid, string pwd)
        {
            if (UserManager == null || TokenManager == null) return null;
            UserIdentifier user = UserManager.Find(lid);
            if (user == null || user.Password != pwd)
            {
                return null;
            }
            else
            {
                string token = TokenManager.New();
                TokenManager.Register(token, user.UniqueId);
                return token;
            }
        }

        public virtual int Logout(string token)
        {
            if (TokenManager == null) return int.MinValue;
            return TokenManager.Unregister(token);
        }

        public virtual string GetUId(string token)
        {
            if (TokenManager == null) return null;
            UserSession session = TokenManager.GetSession(token);
            return session == null ? null : (session.UniqueId == null ? null : session.UniqueId.ToString());
        }

        public ITokenManager TokenManager { get; set; }
        public IUserManager UserManager { get; set; }

        #endregion
    }
}
